package com.steven.image.controller;

import com.alibaba.fastjson.JSONObject;
import com.steven.image.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
public class ImageController {

    @Autowired
    private ImageService service;

    @RequestMapping(value = "/image/icon", method = RequestMethod.GET)
    @ResponseBody
    public void showIconImage(@RequestParam String url, HttpServletResponse response) {
        System.out.println(url);
        if (url.startsWith("/root/java/")) {
            FileInputStream fis = null;
            OutputStream os = null;
            File file = new File(url);
            if (file.exists()) {
                try {
                    fis = new FileInputStream(file);
                    long size = file.length();
                    byte[] temp = new byte[(int) size];
                    fis.read(temp, 0, (int) size);

                    fis.close();
                    byte[] data = temp;
                    response.setContentType("image/png");
                    os = response.getOutputStream();
                    os.write(data);
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                response.sendError(500, "非法请求");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/image/icon/upload")
    public JSONObject uploadStudent(MultipartFile image, @RequestHeader("uid") Long uid, HttpServletResponse response) throws IOException {
        if (uid == null || image == null) {
            response.sendError(500, "请求错误");
            return null;
        }
        return service.uploadIcon(image, uid);
    }

    @PostMapping("/image/queryUrl")
    public JSONObject queryUserIconUrl(@RequestHeader("uid") Long uid, HttpServletResponse response) throws IOException {
        if (uid == null) {
            response.sendError(500, "请求错误");
            return null;
        }
        return service.queryUserIconUrl(uid);
    }
}
